#!/bin/sh
#
# Copyright (c) 2022 Unionman Technology Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e

FILE_PWD=$0
TMP_PATH=${FILE_PWD%/*}
TOOLS_PATH=${TMP_PATH%/*}/tools
echo "Tools path is $TOOLS_PATH"

export PATH=$TOOLS_PATH/mke2fs/bin:$TOOLS_PATH/pack/bin:$TOOLS_PATH/mkimage:$TOOLS_PATH/mkenvimage:$TOOLS_PATH/mtools:$PATH
export LD_LIBRARY_PATH=$TOOLS_PATH/mke2fs/lib:$TOOLS_PATH/pack/lib:$LD_LIBRARY_PATH
export MKE2FS_CONFIG=$TOOLS_PATH/mke2fs/etc/mke2fs.conf


ROOTFS_DIR=$1
ROOT_OUT_DIR=${ROOTFS_DIR%/*}
export ROOT_OUT_DIR

ROOTFS=rootfs.ext4
ROOTFS_SIZE=256M
FAKEROOT_SCRIPT=$ROOT_OUT_DIR/_fakeroot.fs

USERFS_DIR=$ROOT_OUT_DIR/userfs
USERFS=userfs.ext4
USERFS_SIZE=64M

echo "Making rootfs image (size: $ROOTFS_SIZE)..."
rm -f $FAKEROOT_SCRIPT
rm -f $ROOT_OUT_DIR/$ROOTFS
echo "#/bin/sh" >> $FAKEROOT_SCRIPT
echo "set -e" >>  $FAKEROOT_SCRIPT
echo "chown -h -R 0:0 $ROOTFS_DIR" >> $FAKEROOT_SCRIPT
echo "chmod -R 777 $ROOTFS_DIR" >> $FAKEROOT_SCRIPT
echo "mke2fs -d $ROOTFS_DIR -r 1 -N 0 -m 0 -L rootfs -O ^64bit $ROOT_OUT_DIR/$ROOTFS \"$ROOTFS_SIZE\"" >> $FAKEROOT_SCRIPT
chmod a+x $FAKEROOT_SCRIPT
fakeroot -- $FAKEROOT_SCRIPT
echo "Making rootfs image done."

echo "Making userfs image (size: $STORAGEFS_SIZE)..."

rm -rf $USERFS_DIR
mkdir -p $USERFS_DIR
cp $ROOT_OUT_DIR/data $USERFS_DIR -a

rm -f $FAKEROOT_SCRIPT
rm -f $ROOT_OUT_DIR/$USERFS
echo "#/bin/sh" >> $FAKEROOT_SCRIPT
echo "set -e" >>  $FAKEROOT_SCRIPT
echo "chown -h -R 0:0 $USERFS_DIR" >> $FAKEROOT_SCRIPT
echo "chmod -R 777 $USERFS_DIR" >> $FAKEROOT_SCRIPT
echo "mke2fs -d $USERFS_DIR -r 1 -N 0 -m 0 -L userfs -O ^64bit $ROOT_OUT_DIR/$USERFS \"$USERFS_SIZE\"" >> $FAKEROOT_SCRIPT
chmod a+x $FAKEROOT_SCRIPT
fakeroot -- $FAKEROOT_SCRIPT
echo "Making userfs image done."

rm -f $FAKEROOT_SCRIPT

echo "*************** Build UnionPi Lion Package ***************"

make -C $ROOT_OUT_DIR

